# plugs/quote.py
#
#

""" quotes plugin """

__copyright__ = 'this file is in the public domain'

from gozerbot.persist import Persist
from gozerbot.nextid import nextid
from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.datadir import datadir
from gozerbot.generic import lockdec
from gozerbot.plughelp import plughelp
from gozerbot.aliases import aliases
import random, re, time, thread

plughelp.add('quote', 'manage quotes')

class Quoteitem(object):

    """ object representing a quote """

    def __init__(self, idnr, txt, nick=None, userhost=None, ttime=None):
        self.id = idnr
        self.txt = txt
        self.nick = nick
        self.userhost = userhost
        self.time = ttime

quoteslock = thread.allocate_lock()
locked = lockdec(quoteslock)

class Quotes(Persist):

    """ list of quotes """

    @locked
    def __init__(self, fname):
        Persist.__init__(self, fname)
        if not self.data:
            self.data = []

    def size(self):
        """ return nr of quotes """
        return len(self.data)

    @locked
    def add(self, nick, userhost, quote):
        """ add a quote """
        id = nextid.next('quotes')
        item = Quoteitem(id, quote, nick, userhost, \
time.time())
        self.data.append(item)
        self.save()
        return id

    @locked
    def addnosave(self, nick, userhost, quote, ttime):
        """ add quote but don't call save """
        id = nextid.next('quotes')
        item = Quoteitem(nextid.next('quotes'), quote, nick, userhost, ttime)
        self.data.append(item)
        return id

    @locked
    def delete(self, quotenr):
        """ delete quote with id == nr """
        for i in range(len(self.data)):
            if self.data[i].id == quotenr:
                del self.data[i]
                self.save()
                return 1

    def random(self):
        """ get random quote """
        if not self.data:
            return None
        quotenr = random.randint(0, len(self.data)-1)
        return self.data[quotenr]

    def idquote(self, quotenr):
        """ get quote by id """
        for i in self.data:
            if i.id == quotenr:
                return i

    def whoquote(self, quotenr):
        """ get who quoted the quote """
        for i in self.data:
            if i.id == quotenr:
                return (i.nick, i.time)

    def last(self):
        """ get last quote """
        quoteid = 0
        result = None
        for i in self.data:
            if i.id >= quoteid:
                quoteid = i.id
                result = i
        return result

    def search(self, what):
        """ search quotes """
        if not self.data:
            return []
        result = []
        andre = re.compile('and', re.I)
        ands = re.split(andre, what)
        got = 0
        for i in self.data:
            for item in ands:
                if i.txt.find(item.strip()) == -1:
                    got = 0
                    break  
                got = 1
            if got:                  
                result.append(i)
        return result

quotes = Quotes(datadir + '/quotes')

def handle_quoteadd(bot, ievent):
    """ quote-add <txt> .. add a quote """
    if not ievent.rest:
        ievent.missing("<quote>")
        return
    id = quotes.add(ievent.nick, ievent.userhost, ievent.rest)
    ievent.reply('quote %s added' % id)

cmnds.add('quote-add', handle_quoteadd, 'USER')
examples.add('quote-add', 'quote-add <txt> .. add quote', 'quote-add mekker')
aliases.data['aq'] = 'quote-add'

def handle_quotewho(bot, ievent):
    """ quote-who <nr> .. show who added a quote """
    try:
        quotenr = int(ievent.args[0])
    except IndexError:
        ievent.missing("<nr>")
        return
    except ValueError:
        ievent.reply("argument must be an integer")
        return
    result = quotes.whoquote(quotenr)
    if not result[0] or not result[1]:
        ievent.reply('no who quote data available')
        return
    ievent.reply('quote #%s was made by %s on %s' % (quotenr, \
result[0], time.ctime(result[1])))

cmnds.add('quote-who', handle_quotewho, ['USER', 'WEB'])
examples.add('quote-who', 'quote-who <nr> .. show who quote <nr>', \
'quote-who 1')
aliases.data['wq'] = 'quote-who'

def handle_quotedel(bot, ievent):
    """ quote-del <nr> .. delete quote by id """
    try:
        quotenr = int(ievent.args[0])
    except IndexError:
        ievent.missing('<nr>')
        return
    except ValueError:
        ievent.reply('argument needs to be an integer')
        return
    if quotes.delete(quotenr):
        ievent.reply('quote deleted')
    else:
        ievent.reply("can't delete quote with nr %s" % quotenr)

cmnds.add('quote-del', handle_quotedel, ['QUOTE', 'OPER'])
examples.add('quote-del', 'quote-del <nr> .. delete quote', 'quote-del 2')
aliases.data['dq'] = 'quote-del'

def handle_quotelast(bot, ievent):
    """ quote-last .. show last quote """
    quote = quotes.last()
    if quote != None:
        ievent.reply('#%s %s' % (quote.id, quote.txt))
    else:
        ievent.reply("can't fetch quote")

cmnds.add('quote-last', handle_quotelast, ['USER', 'WEB'])
examples.add('quote-last', 'show last quote', 'quote-last')
aliases.data['lq'] = 'quote-last'

def handle_quote2(bot, ievent):
    """ quote-2 .. show 2 random quotes """
    quote = quotes.random()
    if quote != None:
        ievent.reply('#%s %s' % (quote.id, quote.txt))
    else:
        ievent.reply('no quotes yet')
        return
    quote = quotes.random()
    if quote != None:
        ievent.reply('#%s %s' % (quote.id, quote.txt))

cmnds.add('quote-2', handle_quote2, ['USER', 'WEB'])
examples.add('quote-2', 'quote-2 .. show 2 random quotes', 'quote-2')
aliases.data['2q'] = 'quote-2'

def handle_quoteid(bot, ievent):
    """ quote-id <nr> .. show quote by id """
    try:
        quotenr = int(ievent.args[0])
    except IndexError:
        ievent.missing('<nr>')
        return
    except ValueError:
        ievent.reply('argument must be an integer')
        return
    quote = quotes.idquote(quotenr)
    if quote != None:
        ievent.reply('#%s %s' % (quote.id, quote.txt))
    else:
        ievent.reply("can't fetch quote with id %s" % quotenr)

cmnds.add('quote-id', handle_quoteid, ['USER', 'WEB'])
examples.add('quote-id', 'quote-id <nr> .. get quote <nr>', 'quote-id 2')
aliases.data['iq'] = 'quote-id'

def handle_quote(bot, ievent):
    """ quote .. show random quote """
    quote = quotes.random()
    if quote != None:
        ievent.reply('#%s %s' % (quote.id, quote.txt))
    else:
        ievent.reply('no quotes yet')

cmnds.add('quote', handle_quote, ['USER', 'WEB'])
examples.add('quote', 'show random quote', 'quote')
aliases.data['q'] = 'quote'

def handle_quotesearch(bot, ievent):
    """ quote-search <txt> .. search quotes """
    if not ievent.rest:
        ievent.missing('<item>')
        return
    else:
        what = ievent.rest
        nrtimes = 3
    result = quotes.search(what)
    if result:
        if nrtimes > len(result):
            nrtimes = len(result)
        randquotes = random.sample(result, nrtimes)
        for quote in randquotes:
            ievent.reply("#%s %s" % (quote.id, quote.txt))
    else:
        ievent.reply('no quotes found with %s' % what)

cmnds.add('quote-search', handle_quotesearch, ['USER', 'WEB'])
examples.add('quote-search', 'quote-search <txt> .. search quotes for <txt>'\
, 'quote-search bla')
aliases.data['sq'] = 'quote-search'

def handle_quotescount(bot, ievent):
    """ quote-count .. show number of quotes """
    ievent.reply('quotes count is %s' % quotes.size())

cmnds.add('quote-count', handle_quotescount, ['USER', 'WEB'])
examples.add('quote-count', 'count nr of quotes', 'quote-count')
aliases.data['cq'] = 'quote-count'
